package com.mycat.chat.one;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * 聊天客户端
 *
 * @author roger.
 * @email 190642964@qq.com
 * @create 2017-02-10
 */
public class ChatClient extends Frame {

    public static void main(String[] args) {
        new ChatClient().launchFrame();
    }

    // 发送数据框
    TextField sendText = new TextField();
    // 接收数据框
    TextArea receiveText = new TextArea();
    // 连接服务端
    Socket socket = null;
    // 数据传输流对象
    ObjectOutputStream output = null;

    ObjectInputStream input = null;

    /**
     * 初始化窗口
     */
    public void launchFrame() {
        this.setLocation(500, 300);
        this.setSize(800, 520);
        this.add(sendText, BorderLayout.SOUTH);
        this.add(receiveText, BorderLayout.NORTH);
        this.pack();

        // 开启窗口关闭按钮
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                disConnect();
                System.exit(0);
            }
        });

        // 添加发送数据的框的回车监听
        sendText.addActionListener(new SendTextListener());
        this.setVisible(true);
        // 连接服务器
        connectServer();

        new Thread(new ChatClientImporter(input)).start();
    }

    /**
     * 关闭连接
     */
    public void disConnect() {
        try {
            if (null != output) {
                output.close();
            }
            if (null != input) {
                input.close();
            }
            if (null != socket) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接消息服务器
     */
    public void connectServer() {
        try {
            socket = new Socket("localhost", 8888);
            output = new ObjectOutputStream(socket.getOutputStream());
            input = new ObjectInputStream(socket.getInputStream());
            System.out.println("connected!!!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class ChatClientImporter implements Runnable {

        private ObjectInputStream input = null;

        public ChatClientImporter(ObjectInputStream input) {
            this.input = input;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    String message = input.readUTF();
                    System.out.println("客户端收到服务端消息：" + message);

                    String allText = receiveText.getText().trim();
                    if (null == allText || "".equals(allText)) {
                        receiveText.append(message);
                    } else {
                        receiveText.append("\n" + message);
                    }


                }
            } catch (Exception e) {
                System.out.println("current client close!!!");
            } finally {
            }
        }

    }

    /**
     * 向服务端写数据
     *
     * @param data message
     */
    public void sendMessage(String data) {
        try {
            output.writeUTF(data);
            output.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送数据框的回车事件监控
     */
    private class SendTextListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent event) {
            String sendMessage = sendText.getText().trim();

            String allText = receiveText.getText().trim();
            if (null == allText || "".equals(allText)) {
                receiveText.append(sendMessage);
            } else {
                receiveText.append("\n" + sendMessage);
            }

            sendText.setText("");

            sendMessage(sendMessage);
        }
    }

}
